<template>
  <el-card>
    <div class="order-header">
      <el-tabs v-model="orderTab">
        <el-tab-pane label="全部订单" name="all">
          <template #label>
            <span>全部订单 <el-badge v-if="orders.all.length > 0" :value="orders.all.length" type="danger" /></span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="当前订单" name="current">
          <template #label>
            <span>当前订单 <el-badge v-if="orders.current.length > 0" :value="orders.current.length" type="primary" /></span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="历史订单" name="history">
          <template #label>
            <span>历史订单 <el-badge v-if="orders.history.length > 0" :value="orders.history.length" type="success" /></span>
          </template>
        </el-tab-pane>
        <el-tab-pane label="取消/退款订单" name="cancelled">
          <template #label>
            <span>取消/退款订单 <el-badge v-if="orders.cancelled.length > 0" :value="orders.cancelled.length" type="info" /></span>
          </template>
        </el-tab-pane>
      </el-tabs>
      
      <div class="order-actions">
        <el-dropdown @command="handleExportCommand" trigger="click" :disabled="exporting">
          <el-button type="primary" :icon="Download" :loading="exporting">
            {{ exporting ? '导出中...' : '导出订单' }} <el-icon class="el-icon--right" v-if="!exporting"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="current">导出当前标签页订单</el-dropdown-item>
              <el-dropdown-item command="all">导出全部订单</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div v-if="orderTab === 'all'">
      <el-table v-loading="loading" :data="orders.all" style="width: 100%">
        <el-table-column prop="orderNumber" label="订单号" width="120" />
        <el-table-column prop="hotel" label="酒店" />
        <el-table-column prop="roomType" label="房型" />
        <el-table-column prop="checkIn" label="入住日期" />
        <el-table-column prop="checkOut" label="离店日期" />
        <el-table-column prop="totalPrice" label="金额">
          <template #default="scope">
            ¥{{ scope.row.totalPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
            <el-button v-if="scope.row.status === '待支付'" size="small" type="primary" @click="payOrder(scope.row)">支付</el-button>
            <el-button v-if="['待支付', '待入住'].includes(scope.row.status)" size="small" type="danger" @click="cancelOrder(scope.row)">取消</el-button>
            <el-button v-if="scope.row.status === '已完成' && !scope.row.hasReviewed" size="small" @click="rateOrder(scope.row)">评价</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="orders.all.length === 0 && !loading" description="暂无订单" />
    </div>

    <div v-if="orderTab === 'current'">
      <el-table v-loading="loading" :data="orders.current" style="width: 100%">
        <el-table-column prop="orderNumber" label="订单号" width="120" />
        <el-table-column prop="hotel" label="酒店" />
        <el-table-column prop="roomType" label="房型" />
        <el-table-column prop="checkIn" label="入住日期" />
        <el-table-column prop="checkOut" label="离店日期" />
        <el-table-column prop="totalPrice" label="金额">
          <template #default="scope">
            ¥{{ scope.row.totalPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
            <el-button v-if="scope.row.status === '待支付'" size="small" type="primary" @click="payOrder(scope.row)">支付</el-button>
            <el-button v-if="['待支付', '待入住'].includes(scope.row.status)" size="small" type="danger" @click="cancelOrder(scope.row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="orders.current.length === 0 && !loading" description="暂无当前订单" />
    </div>

    <div v-if="orderTab === 'history'">
      <el-table v-loading="loading" :data="orders.history" style="width: 100%">
        <el-table-column prop="orderNumber" label="订单号" width="120" />
        <el-table-column prop="hotel" label="酒店" />
        <el-table-column prop="roomType" label="房型" />
        <el-table-column prop="checkIn" label="入住日期" />
        <el-table-column prop="checkOut" label="离店日期" />
        <el-table-column prop="totalPrice" label="金额">
          <template #default="scope">
            ¥{{ scope.row.totalPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
            <el-button v-if="!scope.row.hasReviewed" size="small" @click="rateOrder(scope.row)">评价</el-button>
            <el-button size="small" type="primary" @click="bookAgain(scope.row)">再次预订</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="orders.history.length === 0 && !loading" description="暂无历史订单" />
    </div>

    <div v-if="orderTab === 'cancelled'">
      <el-table v-loading="loading" :data="orders.cancelled" style="width: 100%">
        <el-table-column prop="orderNumber" label="订单号" width="120" />
        <el-table-column prop="hotel" label="酒店" />
        <el-table-column prop="roomType" label="房型" />
        <el-table-column prop="checkIn" label="入住日期" />
        <el-table-column prop="checkOut" label="离店日期" />
        <el-table-column prop="totalPrice" label="金额">
          <template #default="scope">
            ¥{{ scope.row.totalPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cancelReason" label="取消原因" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewOrderDetail(scope.row)">详情</el-button>
            <el-button size="small" type="primary" @click="bookAgain(scope.row)">再次预订</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="orders.cancelled.length === 0 && !loading" description="暂无取消/退款订单" />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { apiGetUserBookings, apiCancelBooking, apiGetBookingDetail } from '@/api/api'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { Download, ArrowDown } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'

// 定义订单数据类型
interface BookingItem {
  id: string | number;
  orderNumber: string;
  hotelId: string | number;
  hotel: string;
  roomType: string;
  roomId: number;
  checkIn: string;
  checkOut: string;
  guestCount: number;
  totalPrice: number;
  status: string;
  originalStatus: string;
  payStatus: number;
  hasReviewed: boolean;
  createTime: string;
  updateTime: string;
  cancelReason?: string;
}

const router = useRouter()
const orderTab = ref('all') // 默认显示全部订单
const loading = ref(false)
const exporting = ref(false)

// 订单数据
const orders = ref({
  all: [] as BookingItem[],
  current: [] as BookingItem[],
  history: [] as BookingItem[],
  cancelled: [] as BookingItem[]
})

// 获取用户所有订单
const fetchUserBookings = async () => {
  loading.value = true
  try {
    const res:any = await apiGetUserBookings()
    if (res.code === 200) {
      const allBookings = res.data
      console.log('获取到的订单数据:', allBookings)
      
      // 处理可能的状态映射
      const processedBookings = allBookings.map((booking: any) => {
        // 保存原始状态
        const originalStatus = booking.status
        
        // 将后端的状态转换为前端显示的状态
        let status = booking.status
        if (status === 'booked' && booking.payStatus === 0) {
          status = '待支付'
        } else if (status === 'booked' && booking.payStatus === 1) {
          status = '待入住'
        } else if (status === 'checked_in') {
          status = '已入住'
        } else if (status === 'completed' || status === 'confirmed') {
          status = '已完成'
        } else if (status === 'cancelled') {
          status = '已取消'
        }

        // 返回处理后的数据
        return {
          id: booking.bookingId || booking.id,
          orderNumber: booking.orderNo || booking.orderNumber,
          hotelId: booking.hotelId,
          hotel: booking.hotelName || booking.hotel,
          roomType: booking.roomType,
          roomId: booking.roomId,
          checkIn: booking.checkIn ? (typeof booking.checkIn === 'string' ? booking.checkIn.substring(0, 10) : booking.checkIn) : '',
          checkOut: booking.checkOut ? (typeof booking.checkOut === 'string' ? booking.checkOut.substring(0, 10) : booking.checkOut) : '',
          guestCount: booking.guestCount,
          totalPrice: booking.totalPrice,
          status: status,
          originalStatus: originalStatus,
          payStatus: booking.payStatus,
          hasReviewed: booking.hasReviewed || false,
          createTime: booking.createdAt || booking.createTime,
          updateTime: booking.updatedAt || booking.updateTime,
          cancelReason: booking.cancelReason || ''
        }
      })
      
      // 所有订单
      orders.value.all = processedBookings
      
      // 根据状态分类订单
      orders.value.current = processedBookings.filter((order:any) => 
        ['待支付', '待入住', '已入住'].includes(order.status)
      )
      
      orders.value.history = processedBookings.filter((order:any) => 
        ['已完成'].includes(order.status)
      )
      
      orders.value.cancelled = processedBookings.filter((order: any) => 
        ['已取消'].includes(order.status)
      )
    } else {
      ElMessage.error(res.message || '获取订单数据失败')
    }
  } catch (error) {
    ElMessage.error('获取订单数据失败')
    console.error('获取订单数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 查看订单详情
async function viewOrderDetail(order: BookingItem) {
  try {
    const res:any = await apiGetBookingDetail(order.id)
    if (res.code === 200) {
      console.log('订单详情数据:', res.data)
      const bookingDetail = res.data
      
      // 处理入住人信息显示
      let travelersHtml = ''
      if (bookingDetail.travelers && bookingDetail.travelers.length > 0) {
        travelersHtml = `<p><strong>入住人信息:</strong></p><ul>`
        bookingDetail.travelers.forEach((traveler: any) => {
          travelersHtml += `<li>${traveler.name || traveler.travelerId} - ${traveler.idCard}</li>`
        })
        travelersHtml += `</ul>`
      }
      
      // 处理评价信息显示
      let reviewHtml = ''
      if (bookingDetail.review) {
        const review = bookingDetail.review
        reviewHtml = `
          <p><strong>评价信息:</strong></p>
          <p>评分: ${review.rating} 星</p>
          <p>内容: ${review.content}</p>
        `
      }
      
      // 处理订单状态显示
      let status = bookingDetail.status || order.status
      if (status === 'booked' && (bookingDetail.payStatus === 0 || order.status === '待支付')) {
        status = '待支付'
      } else if (status === 'booked' && (bookingDetail.payStatus === 1 || order.status === '已付款' || order.status === '待入住')) {
        status = '待入住'
      } else if (status === 'checked_in' || status === '已入住') {
        status = '已入住'
      } else if (status === 'completed' || status === 'confirmed' || status === '已完成') {
        status = '已完成'
      } else if (status === 'cancelled' || status === '已取消') {
        status = '已取消'
      }
      
      ElMessageBox.alert(
        `
        <div>
          <p><strong>订单号:</strong> ${bookingDetail.orderNumber || bookingDetail.orderNo || order.orderNumber}</p>
          <p><strong>酒店名称:</strong> ${bookingDetail.hotel || bookingDetail.hotelName || order.hotel}</p>
          <p><strong>房间类型:</strong> ${bookingDetail.roomType || order.roomType}</p>
          <p><strong>入住日期:</strong> ${bookingDetail.checkIn ? (typeof bookingDetail.checkIn === 'string' ? bookingDetail.checkIn.substring(0, 10) : bookingDetail.checkIn) : order.checkIn}</p>
          <p><strong>离店日期:</strong> ${bookingDetail.checkOut ? (typeof bookingDetail.checkOut === 'string' ? bookingDetail.checkOut.substring(0, 10) : bookingDetail.checkOut) : order.checkOut}</p>
          <p><strong>订单状态:</strong> ${status}</p>
          <p><strong>订单总价:</strong> ¥${bookingDetail.totalPrice || order.totalPrice}</p>
          <p><strong>入住人数:</strong> ${bookingDetail.guestCount || order.guestCount}人</p>
          <p><strong>创建时间:</strong> ${bookingDetail.createTime || bookingDetail.createdAt || order.createTime}</p>
          ${bookingDetail.cancelReason ? `<p><strong>取消原因:</strong> ${bookingDetail.cancelReason}</p>` : ''}
          ${travelersHtml}
          ${reviewHtml}
        </div>
        `,
        '订单详情',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          closeOnClickModal: true
        }
      )
    } else {
      ElMessage.error(res.message || '获取订单详情失败')
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败')
    console.error('获取订单详情失败:', error)
  }
}

// 取消订单
async function cancelOrder(order: BookingItem) {
  try {
    await ElMessageBox.confirm('确认取消该订单吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res:any = await apiCancelBooking(order.id)
    if (res.code === 200) {
      ElMessage.success('订单已成功取消')
      fetchUserBookings() // 重新获取订单列表
    } else {
      ElMessage.error(res.message || '取消订单失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消订单失败')
      console.error('取消订单失败:', error)
    }
  }
}

// 支付订单
async function payOrder(order: any) {
  try {
    window.location.href = "http://localhost:8080/payment/create/"+order.id;
   
  } catch (error) {
    ElMessage.error('创建支付订单失败')
    console.error('创建支付订单失败:', error)
  }
}

// 评价订单
function rateOrder(order: BookingItem) {
  // 跳转到评价页面
  router.push({
    name: 'add-review',
    params: { 
      bookingId: order.id.toString(),
      hotelId: order.hotelId.toString()
    },
    query: {
      hotel: order.hotel,
      roomType: order.roomType
    }
  });
}

// 再次预订
function bookAgain(order: BookingItem) {
  // 跳转到预订页面，带上之前的酒店信息
  console.log(order.hotelId);
  
  router.push({
    name: 'hotel-detail',
    params: { id: order.hotelId.toString() }
  })
}

// 根据订单状态返回不同的标签类型
function getStatusTagType(status: string) {
  switch (status) {
    case '待支付':
      return 'warning'
    case '待入住':
      return 'primary'
    case '已入住':
      return 'success'
    case '已完成':
      return 'success'
    case '已取消':
      return 'info'
    default:
      return ''
  }
}

// 获取当前要导出的订单数据
const currentExportData = computed(() => {
  switch (orderTab.value) {
    case 'all':
      return orders.value.all
    case 'current':
      return orders.value.current
    case 'history':
      return orders.value.history
    case 'cancelled':
      return orders.value.cancelled
    default:
      return []
  }
})

// 所有订单数据
const allOrders = computed(() => {
  return orders.value.all
})

// 导出下拉菜单处理
function handleExportCommand(command: string) {
  if (command === 'current') {
    exportToExcel(currentExportData.value, getOrderTabName())
  } else if (command === 'all') {
    exportToExcel(allOrders.value, '全部')
  }
}

// 导出Excel函数
function exportToExcel(data: BookingItem[], tabName: string) {
  // 如果没有数据，提示用户
  if (data.length === 0) {
    ElMessage.warning('当前没有可导出的订单数据')
    return
  }

  exporting.value = true
  ElMessage.info(`开始导出${tabName}订单，共 ${data.length} 条记录`)

  try {
    // 准备导出数据
    const exportData = data.map(order => {
      return {
        '订单号': order.orderNumber,
        '酒店': order.hotel,
        '房型': order.roomType,
        '入住日期': order.checkIn,
        '离店日期': order.checkOut,
        '入住人数': order.guestCount,
        '金额(¥)': order.totalPrice,
        '状态': order.status,
        '创建时间': order.createTime
      }
    })

    // 创建工作簿和工作表
    const wb = XLSX.utils.book_new()
    const ws = XLSX.utils.json_to_sheet(exportData)

    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 订单号
      { wch: 20 }, // 酒店
      { wch: 15 }, // 房型
      { wch: 12 }, // 入住日期
      { wch: 12 }, // 离店日期
      { wch: 10 }, // 入住人数
      { wch: 10 }, // 金额
      { wch: 10 }, // 状态
      { wch: 20 }  // 创建时间
    ]
    ws['!cols'] = colWidths

    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, `${tabName}订单`)

    // 生成Excel文件并下载
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
    const blob = new Blob([excelBuffer], { type: 'application/octet-stream' })
    
    // 生成文件名
    const now = new Date()
    const dateStr = `${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}`
    const timeStr = `${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`
    const fileName = `订单导出_${tabName}_${dateStr}_${timeStr}.xlsx`
    
    // 设置超时，确保用户有足够的视觉反馈
    setTimeout(() => {
      FileSaver.saveAs(blob, fileName)
      ElMessage.success(`成功导出 ${data.length} 条订单记录`)
      exporting.value = false
    }, 500)
  } catch (error) {
    console.error('导出Excel失败:', error)
    ElMessage.error('导出Excel失败')
    exporting.value = false
  }
}

// 获取当前标签页名称
function getOrderTabName() {
  switch (orderTab.value) {
    case 'all':
      return '全部'
    case 'current':
      return '当前'
    case 'history':
      return '历史'
    case 'cancelled':
      return '取消'
    default:
      return '全部'
  }
}

// 页面加载时获取订单数据
onMounted(() => {
  fetchUserBookings()
})
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.order-actions {
  display: flex;
  gap: 10px;
}

/* 确保表格内容垂直居中 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
}

/* 调整标签页样式 */
:deep(.el-tabs__nav) {
  margin-left: 0;
}
</style> 